from datetime import date
from typing import Sequence
import pandas as pd
from sqlalchemy import delete, desc, insert, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from module_stock.entity.do.daily_do import StockDaily
from module_stock.entity.vo.daily_vo import DailyModel, DailyPageQueryModel
from utils.page_util import PageUtil
from config.database  import engine
from utils.pd_util import AsyncORMConverter

class DailyDao:
    """
    股票日线模块数据库操作层
    """

    @classmethod
    async def get_daily_detail_by_id(cls, db: AsyncSession, id: int):
        """
        根据id获取股票日线详细信息

        :param db: orm对象
        :param id: id
        :return: 股票日线信息对象
        """
        daily_info = (
            (
                await db.execute(
                    select(StockDaily)
                    .where(
                        StockDaily.id == id
                    )
                )
            )
            .scalars()
            .first()
        )

        return daily_info

    @classmethod
    async def get_daily_detail_by_info(cls, db: AsyncSession, daily: DailyModel):
        """
        根据股票日线参数获取股票日线信息

        :param db: orm对象
        :param daily: 股票日线参数对象
        :return: 股票日线信息对象
        """
        daily_info = (
            (
                await db.execute(
                    select(StockDaily).where(
                    )
                )
            )
            .scalars()
            .first()
        )

        return daily_info
    
    @classmethod
    async def get_last_daily_detail(cls, db: AsyncSession, symbol: str):
        """
        根据股票代码获取数据表最后一个日线信息

        :param db: orm对象
        :param symbol: 股票代码
        :return: 股票日线信息对象
        """
        daily_info = (
            (
                await db.execute(
                    select(StockDaily).where(
                        StockDaily.symbol == symbol
                    ).order_by(desc(StockDaily.trade_date)).limit(1)
                )
            )
            .scalars()
            .first()
        )

        return daily_info

    @classmethod
    async def get_daily_list(cls, db: AsyncSession, query_object: DailyPageQueryModel, is_page: bool = False):
        """
        根据查询参数获取股票日线列表信息

        :param db: orm对象
        :param query_object: 查询参数对象
        :param is_page: 是否开启分页
        :return: 股票日线列表信息对象
        """
        query = (
            select(StockDaily)
            .where(
                StockDaily.trade_date == query_object.trade_date if query_object.trade_date else True,
                StockDaily.symbol == query_object.symbol if query_object.symbol else True,
                StockDaily.open == query_object.open if query_object.open else True,
                StockDaily.close == query_object.close if query_object.close else True,
                StockDaily.high == query_object.high if query_object.high else True,
                StockDaily.low == query_object.low if query_object.low else True,
                StockDaily.vol == query_object.vol if query_object.vol else True,
                StockDaily.amount == query_object.amount if query_object.amount else True,
                StockDaily.amplitude == query_object.amplitude if query_object.amplitude else True,
                StockDaily.pct_chg == query_object.pct_chg if query_object.pct_chg else True,
                StockDaily.chg == query_object.chg if query_object.chg else True,
                StockDaily.turn == query_object.turn if query_object.turn else True,
            )
            .order_by(StockDaily.trade_date.desc())
        )
        daily_list = await PageUtil.paginate(db, query, query_object.page_num, query_object.page_size, is_page)

        return daily_list

    @classmethod
    async def get_all_daily(cls, db: AsyncSession, symbol:str):
        """
        获取所有股票日线信息

        :param db: orm对象
        :return: 股票信息集
        """
        query = (
            select(StockDaily).where(StockDaily.symbol == symbol)
        )

        daily_list = (await db.execute(query)).scalars().all()

        return daily_list
    
    @classmethod
    async def get_all_daily_after_date(cls, db: AsyncSession, symbol:str, date:date) -> Sequence[StockDaily]:
        """
        获取所有股票日线信息

        :param db: orm对象
        :return: 股票信息集
        """
        query = (
            select(StockDaily).where(
                StockDaily.symbol == symbol,
                StockDaily.trade_date >= date
                ).order_by(StockDaily.trade_date.asc())
        )

        daily_list = (await db.execute(query)).scalars().all()

        return daily_list
    
    @classmethod
    async def get_all_daily_pd(cls, db: AsyncSession, symbol:str):
        """
        获取所有股票日线信息

        :param db: orm对象
        :return: 股票信息集
        """
        query = (
            select(StockDaily).where(StockDaily.symbol == symbol).order_by(StockDaily.trade_date.asc())
        )
        dailys = (await db.execute(query)).scalars().all()
        daily_df = pd.DataFrame(AsyncORMConverter._orms_to_dicts(dailys))
        return daily_df
    
    @classmethod
    async def get_all_daily_pd_after_date(cls, db: AsyncSession, symbol:str, date:date):
        """
        获取所有股票日线信息

        :param db: orm对象
        :return: 股票信息集
        """
        query = (
            select(StockDaily).where(
                StockDaily.symbol == symbol,
                StockDaily.trade_date >= date
                ).order_by(StockDaily.trade_date.asc())
        )

        daily_list = (await db.execute(query)).scalars().all()
        daily_df = pd.DataFrame(AsyncORMConverter._orms_to_dicts(daily_list))
        return daily_df

    @classmethod
    async def get_all_symbols(cls, db: AsyncSession):
        """
        获取所有股票代码

        :param db: orm对象
        :return: 股票代码集
        """
        query = (
            select(StockDaily.symbol).distinct()
            .order_by(StockDaily.symbol)
        )

        symbols = (await db.execute(query)).scalars().all()

        return symbols

    @classmethod
    async def add_daily_dao(cls, db: AsyncSession, daily: DailyModel):
        """
        新增股票日线数据库操作

        :param db: orm对象
        :param daily: 股票日线对象
        :return:
        """
        db_daily = StockDaily(**daily.model_dump(exclude={}))
        db.add(db_daily)
        await db.flush()

        return db_daily
    
    @classmethod
    async def batch_add_daily_dao(cls, db: AsyncSession, dailys: list[dict]):
        """
        批量新增股票基础信息数据库操作

        :param db: orm对象
        :param basics: 股票日线实体对象列表
        :return:
        """
        st = insert(StockDaily).values(dailys)
        await db.execute(st)

    @classmethod
    async def edit_daily_dao(cls, db: AsyncSession, daily: dict):
        """
        编辑股票日线数据库操作

        :param db: orm对象
        :param daily: 需要更新的股票日线字典
        :return:
        """
        await db.execute(update(StockDaily), [daily])

    @classmethod
    async def delete_daily_dao(cls, db: AsyncSession, daily: DailyModel):
        """
        删除股票日线数据库操作

        :param db: orm对象
        :param daily: 股票日线对象
        :return:
        """
        await db.execute(delete(StockDaily).where(
            StockDaily.id.in_([daily.id]) if daily.id else True,
            StockDaily.symbol == daily.symbol if daily.symbol else True
        ))

    @classmethod
    async def batch_delete_daily_dao(cls, db: AsyncSession, symbols):
        """
        批量删除股票基础信息数据库操作

        :param db: orm对象
        :param basic: 股票基础信息对象
        :return:
        """
        await db.execute(delete(StockDaily).where(StockDaily.symbol.in_(symbols)))
